import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './assets/less/index.less'
import store from './store/index.js'
import './api/mock.js'
import api from "./api/api"

const app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

//全局使用api
app.config.globalProperties.$api = api
//动态加载菜单
store.commit('addMenu', router)

//检查路由是否存在
function checkRouter(path) {
    let hasCheck = router.getRoutes().filter(route => route.path == path).length
    //console.log(hasCheck);
    if (hasCheck) {
        return true
    } else {
        return false
    }
}

//路由守卫，验证是否登录及路由是否存在跳转的地址
router.beforeEach((to, from, next) => {
    store.commit('getToken')
    //console.log(to.name);
    const token = store.state.token
    if (!token && to.name !== 'login') {
        next({ name: 'login' })
    } else if (!checkRouter(to.path)) {
        next({ name: 'home' })
    } else {
        next()
    }
})
app.use(router).use(store)
app.mount('#app')
